//
//  NetStatisticViewController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/4/5.
//  Copyright © 2016年 hanen. All rights reserved.
//网点统计

#import "NetStatisticViewController.h"
#import "ChartView.h"
#import "NetInfoViewCell.h"
#import "SideMenuUtil.h"

#define RandColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0]

@interface NetStatisticViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

{
    UIView  *_topView;
    
    UIView  *_midChartView;
    NSInteger precentCount;
    NSArray *array;
    ChartView * chartV ;
    NSMutableArray *arr;
    
    
    UIView  *_infoView;
    UITableView *_tablview;
    
    UIScrollView  *_scrollView;
    UIPageControl *pageControl;
    
    UIView *_placeView;
    UIPickerView *_placePickerView;
    UIButton *locaBtn;
    
    NSString *proStr;
    NSString *city;
    NSString *regionStr;
    
    int proID;//省ID
    int cityID;//市ID
    
    NSMutableArray *dataArray;
    NSMutableArray * olorArray;
    
    NSMutableArray * branchArray;
    NSArray        *titleArr;
}
@property (strong, nonatomic) NSMutableArray *provinceArray;
@property (strong, nonatomic) NSMutableArray *cityArray;
@property (strong, nonatomic) NSMutableArray *regionArray;
@property (strong, nonatomic) NSMutableArray *selectedArray;

@end

@implementation NetStatisticViewController
@synthesize revealController;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayBackColor;
    self.navigationItem.title = @"竞争对手统计";
    
    self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];
    
    [SideMenuUtil addViewGesture:self revealController:revealController];
    precentCount = 0;

    _provinceArray = [NSMutableArray array];
    _cityArray   = [NSMutableArray array];
    _regionArray = [NSMutableArray array];
    branchArray  = [NSMutableArray array];
    //获取省市区
    [self initCity];
   
    
    [self addPrecentView];
    [self creatCityPickerView];
    
    [self initBranchCount];
}
- (void)initCity{
    NSArray *array1 = @[@{@"region":@"全部"}];
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithDictionary:@{@"region":@"全部",@"city":array1}];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app.region.all" forKey:@"method"];
    [dic setObject:@0 forKey:@"isCache"];
//    if (proDic) {
        [_provinceArray addObject:dic1];
//    }
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"%@+++shengshiqu",jsonDic);
        
        NSDictionary *dataDic = jsonDic[@"data"];
        NSMutableArray *arra = dataDic[@"allRegion"];
        for (int i = 0; i<arra.count; i++) {
            NSDictionary *proDic = arra[i];
            if (proDic) {
            [_provinceArray addObject:proDic];
            }
        
            self.selectedArray = _provinceArray.firstObject[@"city"];
            if (self.selectedArray.count > 0) {
                self.cityArray = _provinceArray.firstObject[@"city"];
            }
            if(self.cityArray.count> 0){
                self.regionArray = self.cityArray.firstObject[@"district"];
            }
            
        }
//        NSLog(@"%@",jsonDic);
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)sideLeftButton_selector:(id)sender {
    
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}
#pragma mark
#pragma mark---------地区选择
- (void)creatCityPickerView{
    
    CGFloat pickerH = 260;
    CGFloat buttonW = 60.0f;
    CGFloat buttonH = 40.0f;
    
    _placeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _placeView.hidden = YES;
    [self.view addSubview:_placeView];
    
    UIView * bgBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight - pickerH)];
    bgBlackView.backgroundColor = [UIColor blackColor];
    bgBlackView.alpha = 0.6;
    [_placeView addSubview:bgBlackView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToHideBlackView:)];
    [bgBlackView addGestureRecognizer:tapGesture];
    
    UIView *pView = [[UIView alloc] initWithFrame:CGRectMake(0, bgBlackView.maxY, kScreenWidth,pickerH)];
    pView.backgroundColor = [UIColor whiteColor];
    [_placeView addSubview:pView];
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0 , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line1];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, line1.maxY, buttonW, buttonH)];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(hanldePlaceSelected:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [ViewTool getFont:15];
    [pView addSubview:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(_placeView.width - 10 - buttonW, line1.maxY , buttonW, buttonH)];
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [ViewTool getFont:15];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(hanldePlaceSelected:) forControlEvents:UIControlEventTouchUpInside];
    [pView addSubview:rightBtn];
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(0, rightBtn.maxY , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line];
    
    _placePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, line.maxY  , kScreenWidth, pView.height - 30-70)];
    [pView addSubview:_placePickerView];
    _placePickerView.delegate = self;
    _placePickerView.dataSource = self;
}
- (void)tapToHideBlackView:(UITapGestureRecognizer *)tap{
    
}

//点击完成
- (void)hanldePlaceSelected:(UIButton *)sender{
    _placeView.hidden = YES;
    
    if (self.provinceArray.count > 0) {
        proStr = [self.provinceArray objectAtIndex:[_placePickerView selectedRowInComponent:0]][@"region"];
    }else{
        proStr = @"";
    }
    
    if (self.cityArray.count > 0) {
        city = [self.cityArray objectAtIndex:[_placePickerView selectedRowInComponent:1]][@"region"];
    }else{
        city = @"";
    }
    
    if ([sender.currentTitle isEqualToString:@"完成"]) {
        
        if ([proStr isEqualToString:city]) {
            [locaBtn setTitle:proStr forState:UIControlStateNormal];
        }else{
            [locaBtn setTitle:[NSString stringWithFormat:@"%@ %@",proStr,city] forState:UIControlStateNormal];
        }
        
        proID = [[self.provinceArray objectAtIndex:[_placePickerView selectedRowInComponent:0]][@"id"] intValue];
        cityID = [[self.cityArray objectAtIndex:[_placePickerView selectedRowInComponent:1]][@"id"] intValue];
        NSLog(@"proID：%d------cityID：%d++++",proID,cityID);
        
        [self initBranchCount];
        
        
    }
    
}
#pragma mark
#pragma mark---------网点统计加载数据
- (void)initBranchCount{
    
    NSMutableDictionary *dic;
    if (cityID == proID) {
        dic = [[NSMutableDictionary alloc]initWithDictionary:@{@"method":@"app.count.branch",@"province_id":@(proID)}];
    }else{
        dic = [[NSMutableDictionary alloc]initWithDictionary:@{@"method":@"app.count.branch",@"province_id":@(proID),@"city_id":@(cityID)}];
    }
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@ 数据00000000+++++++",jsonDic);
        if ([jsonDic[@"status"] isEqualToString:@"ERROR"]) {
            [Tools showMessage:jsonDic[@"msg"] view:self];
            return ;
        }else{
        
        NSArray *signArray = jsonDic[@"data"][@"signs"];
        NSArray *visitArray = jsonDic[@"data"][@"visits"];
        NSArray *levelArray = jsonDic[@"data"][@"levels"];
        NSArray *competitorArray = jsonDic[@"data"][@"competitors"];
        
        NSMutableArray *arr11 = [[NSMutableArray alloc]initWithObjects:competitorArray,levelArray,visitArray,signArray, nil];
        branchArray = arr11;
        
        
        NSMutableArray *coArray1 = [NSMutableArray array];
        NSMutableArray *coArray2 = [NSMutableArray array];
        NSMutableArray *coArray3 = [NSMutableArray array];
        NSMutableArray *coArray4 = [NSMutableArray array];
        
        NSMutableArray *coArray5 = [NSMutableArray array];
        NSMutableArray *coArray6 = [NSMutableArray array];
        NSMutableArray *coArray7 = [NSMutableArray array];
        NSMutableArray *coArray8 = [NSMutableArray array];
        //
        for (int i=0; i<competitorArray.count; i++) {
            NSString *comstr = competitorArray[i][@"percent"];
            [coArray1 addObject:comstr];
            NSString *comstr1 = competitorArray[i][@"name"];
            [coArray5 addObject:comstr1];
        }
        
        ChartView *chatV1 = [_scrollView viewWithTag:999666];
        chatV1.precentArray = coArray1;
        chatV1.percentStr = coArray1[0];
        chatV1.completeStr = coArray5[0];
        chatV1.compeleteArray = coArray5;
        //
        for (int i=0; i<levelArray.count; i++) {
            NSString *comstr2 = levelArray[i][@"percent"];
            [coArray2 addObject:comstr2];
            NSString *comstr3 = levelArray[i][@"level"];
            [coArray6 addObject:comstr3];
        }
        
        ChartView *chatV2 = [_scrollView viewWithTag:999666+1];
        chatV2.precentArray = coArray2;
        chatV2.percentStr = coArray2[0];
        chatV2.completeStr = coArray6[0];
        chatV2.compeleteArray = coArray6;
        //
        for (int i=0; i<visitArray.count; i++) {
            NSString *comstr4 = visitArray[i][@"percent"];
            [coArray3 addObject:comstr4];
            NSString *comstr5 = visitArray[i][@"title"];
            [coArray7 addObject:comstr5];
        }
        
        ChartView *chatV3 = [_scrollView viewWithTag:999666+2];
        chatV3.precentArray = coArray3;
        chatV3.percentStr = coArray3[0];
        chatV3.completeStr = coArray7[0];
        chatV3.compeleteArray = coArray7;
        //
        for (int i=0; i<signArray.count; i++) {
            NSString *comstr6 = signArray[i][@"percent"];
            [coArray4 addObject:comstr6];
            NSString *comstr7 = signArray[i][@"title"];
            [coArray8 addObject:comstr7];
        }
        
        ChartView *chatV4 = [_scrollView viewWithTag:999666+3];
        chatV4.precentArray = coArray4;
        chatV4.percentStr = coArray4[0];
        chatV4.completeStr = coArray8[0];
        chatV4.compeleteArray = coArray8;
        
        [_tablview reloadData];
    }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [Tools showMessage:error.localizedDescription view:self];
    }];
    
}
- (void)clickToSelectRegion:(UIButton *)btn{
    if (btn.selected == NO) {
        [UIView animateWithDuration:0.25 animations:^{
            _placeView.hidden = NO;
        }];
        
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            _placeView.hidden = YES;
        }];
    }
    btn.selected = !btn.selected;
    [_placePickerView reloadAllComponents];
}
- (void)addPrecentView{
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, [UIView getHeight:300.0f])];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollView];
    _scrollView.contentSize=CGSizeMake(kScreenWidth*4, [UIView getHeight:300]);
    _scrollView.delegate=self;
    _scrollView.pagingEnabled=YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    arr = [NSMutableArray arrayWithArray:@[@[@"100"],@[@"100"],@[@"100"],@[@"100"]]];
    dataArray = [NSMutableArray arrayWithArray:@[@[@"无"],@[@"无"],@[@"无"],@[@"无"]]];
    
    titleArr = @[@"竞争对手统计",@"评级统计",@"拜访统计",@"签约统计"];
    NSLog(@"%lu+-+-+--+-brancharray",(unsigned long)branchArray.count);
    for (int i=0; i<titleArr.count; i++) {
        chartV = [[ChartView alloc] initWithFrame:CGRectMake(kScreenWidth*i, 20, kScreenWidth, _scrollView.height)];
        chartV.backgroundColor = [UIColor whiteColor];
        chartV.precentArray = arr[i];
        chartV.tag = 999666+i;
        chartV.title = titleArr[i];
        chartV.percentStr = arr[i][0];
        chartV.completeStr = dataArray[i][0];
        chartV.compeleteArray = dataArray[i];
        [_scrollView addSubview:chartV];
    }
    [_tablview reloadData];
    
    pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake((kScreenWidth-100)/2, _scrollView.height-30, 100, 20)];
    pageControl.numberOfPages = 4;
    pageControl.pageIndicatorTintColor = UIColorFromRGB(0xeceef0);
    pageControl.currentPageIndicatorTintColor = UIColorFromRGB(0xa1a2a6);
    [self.view addSubview:pageControl];
    
    [self addLocationBtn];
    [self addInfoView];
    
}
- (void)addLocationBtn{
    
    locaBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - [UIView  getWidth:20] - 115-6, 30, 100, 30)];
    [locaBtn setTitle:@"全部" forState:UIControlStateNormal];
    [locaBtn setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
    [locaBtn addTarget:self action:@selector(clickToSelectRegion:) forControlEvents:UIControlEventTouchUpInside];
    locaBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    locaBtn.titleLabel.font = [ViewTool getFont:16.0f];
    [self.view addSubview:locaBtn];
    
    
    UIButton *imageBtn = [[UIButton alloc]initWithFrame:CGRectMake(locaBtn.maxX - 5, locaBtn.y-3, 36, 36)];
    [imageBtn setImage:[UIImage imageNamed:@"xuanze"] forState:UIControlStateNormal];
    [imageBtn addTarget:self action:@selector(clickToSelectRegion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imageBtn];
    
}
- (void)changePicCount
{
    [_scrollView setContentOffset:CGPointMake(pageControl.currentPage*kScreenWidth, 0) animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    pageControl.currentPage = _scrollView.contentOffset.x / kScreenWidth;
    int  count = (int)pageControl.currentPage;
    self.navigationItem.title = titleArr[count];
    [_tablview reloadData];
}
- (void)addInfoView
{
    _infoView = [[UIView alloc] initWithFrame:CGRectMake(0, _scrollView.maxY, kScreenWidth, kScreenHeight - _scrollView.maxY - 64)];
    _infoView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:_infoView];
    
    _tablview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _infoView.width, _infoView.height) style:UITableViewStylePlain];
    _tablview.delegate = self;
    _tablview.dataSource = self;
    _tablview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_infoView addSubview:_tablview];
}
#pragma mark
#pragma mark-------tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    int a = (int)pageControl.currentPage;
    if (branchArray.count != 0) {
        return [branchArray[a] count];
    }else{
        return [arr[a] count];

    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NetInfoViewCell *cell = [NetInfoViewCell cellWithTabelView:tableView];
    int a = (int)pageControl.currentPage;
    cell.index = indexPath.section;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (branchArray.count != 0) {
        ChartView *chartvv1 = [_scrollView viewWithTag:999666+a];
        cell.precentColor = chartvv1.colorArray[indexPath.section];
        
        cell.precent = [branchArray[a][indexPath.section][@"percent"] floatValue];
        if (a == 0) {
            cell.nameStr = branchArray[a][indexPath.section][@"name"];
        }else if (a == 1){
            cell.nameStr = branchArray[a][indexPath.section][@"level"];
        }else{
            cell.nameStr = branchArray[a][indexPath.section][@"title"];
        }
        
//        cell.numStr = branchArray[a][indexPath.section][@"num"];
        cell.numStr = [NSString stringWithFormat:@"%ld",indexPath.section + 1];
        
    }else{
        
        ChartView *chartvv = [_scrollView viewWithTag:999666+a];
        cell.precentColor = chartvv.colorArray[indexPath.section];
        cell.precent = [arr[a][indexPath.section] floatValue];
        cell.nameStr = dataArray[a][indexPath.section];
        
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 8.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _infoView.width, 8.0f)];
    view.backgroundColor = GrayBackColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [NetInfoViewCell cellHeight];
}

#pragma mark -- pickView代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 2;
    
}
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
   
    if (component ==0) {
        return _provinceArray.count;
    }else{
        return _cityArray.count;
    }
        
    
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        return _provinceArray[row][@"region"];
    }else {
        return _cityArray[row][@"region"];
    }
    
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
        if (component == 0) {
            
            _selectedArray = self.provinceArray[row][@"city"];
            if (_selectedArray.count > 0) {
                self.cityArray = _selectedArray;
            }else{
                self.cityArray = nil;
            }
            
        }
        [pickerView selectedRowInComponent:1];
        [pickerView reloadComponent:1];
    if (self.provinceArray.count > 0) {
        proStr = [self.provinceArray objectAtIndex:[pickerView selectedRowInComponent:0]][@"region"];
    }
    if (self.cityArray.count > 0) {
        city = [self.cityArray objectAtIndex:[pickerView selectedRowInComponent:1]][@"region"];
    }
    
    
}

- (void)addPrecentToArray
{
    [chartV.precentArray removeAllObjects];
    if (precentCount < array.count) {
        [arr addObject:array[precentCount]];
        precentCount ++;
        NSLog(@"%@",arr[precentCount]);
        chartV.precentArray = arr ;
//        [chartV setNeedsDisplay];
        NSLog(@"%@",array[precentCount]);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
